package org.example.springvalidation;


import org.springframework.context.MessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.method.ParameterValidationResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.*;
import java.util.stream.Collectors;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            errors.put(error.getField(), error.getDefaultMessage());
        }
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
    @ExceptionHandler(HandlerMethodValidationException.class)
    public ResponseEntity<List<String>> handleValidationExceptions(HandlerMethodValidationException ex) {
        Map<String, String> errors = new HashMap<>();
        List<String> errList = new ArrayList<>();
        List<ParameterValidationResult> allValidationResults = ex.getAllValidationResults();
        for (ParameterValidationResult allValidationResult : allValidationResults) {
            List<MessageSourceResolvable> resolvableErrors = allValidationResult.getResolvableErrors();
            String err = resolvableErrors.stream().map(MessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(", "));
            errList.add(err);
        }
        return new ResponseEntity<>(errList, HttpStatus.BAD_REQUEST);
    }
}
